<template>
  <div class="relative">
    <div ref="taskRef" :data-task-id="localTask.id" class="item">
      <em class="priority-color" :style="{ backgroundColor: localTask.pColor }" />
      <div class="flex justify-between">
        <!-- 工作流状态 -->
        <n-select
          v-model:value="currentFlowItemId" :options="options" size="tiny" style="width: 88px;"
          @click.stop="handleSelectClick" @update:value="handleUpdateFlowItem"
        />
        <!-- 任务名称 -->
        <p class="title dark:text-navy-100 tracking-wide" style="width: 114px">
          {{ localTask.name }}
        </p>

        <!--        <svg -->
        <!--          xmlns="http://www.w3.org/2000/svg" -->
        <!--          class="tag dark:text-secondary-light" -->
        <!--          viewBox="0 0 20 20" -->
        <!--          fill="currentColor" -->
        <!--        > -->
        <!--          <path -->
        <!--            fill-rule="evenodd" -->
        <!--            d="M3 6a3 3 0 013-3h10a1 1 0 01.8 1.6L14.25 8l2.55 3.4A1 1 0 0116 13H6a1 1 0 00-1 1v3a1 1 0 11-2 0V6z" -->
        <!--            clip-rule="evenodd" -->
        <!--          /> -->
        <!--        </svg> -->
      </div>

      <p class="desc dark:text-navy-300">
        {{ cleanHtml(localTask.description) }}
      </p>

      <div class="mt-3 flex items-end justify-between">
        <div class="flex flex-wrap -space-x-1.5">
          <n-avatar-group :options="taskUsers" :size="24" :max="4">
            <template #avatar="{ option: { name } }">
              <n-tooltip>
                <template #trigger>
                  <NAvatar
                    round
                    size="small"
                    style="background-color: #4c86f9;color: white"
                  >
                    <!--  {{name.substr(0, 1).toUpperCase() }} -->
                    {{ name }}
                  </NAvatar>
                </template>
                {{ name }}
              </n-tooltip>
            </template>
            <template #rest="{ options: restOptions, rest }">
              <n-dropdown :options="dropdownOptions(restOptions)" placement="top">
                <NAvatar>+{{ rest }}</NAvatar>
              </n-dropdown>
            </template>
          </n-avatar-group>
        </div>

        <div v-if="localTask.endTime" class="time-line">
          <div class="time-box">
            <i class="time-icon i-fe:clock" />
            <span>{{ localTask.endTime.substring(5, 10) }}</span>
          </div>
        </div>
        <!--        <div -->
        <!--          class="dark:text-navy-300 last-text-box flex items-center space-x-2" -->
        <!--        > -->
        <!--          <div class="flex items-center space-x-0.5"> -->
        <!--            <svg -->
        <!--              xmlns="http://www.w3.org/2000/svg" -->
        <!--              class="time-icon" -->
        <!--              fill="none" -->
        <!--              viewBox="0 0 24 24" -->
        <!--              stroke="currentColor" -->
        <!--            > -->
        <!--              <path -->
        <!--                stroke-linecap="round" -->
        <!--                stroke-linejoin="round" -->
        <!--                stroke-width="2" -->
        <!--                d="M7 7h.01M7 3h5c.512 0 1.024.195 1.414.586l7 7a2 2 0 010 2.828l-7 7a2 2 0 01-2.828 0l-7-7A1.994 1.994 0 013 12V7a4 4 0 014-4z" -->
        <!--              /> -->
        <!--            </svg> -->
        <!--            <span>2</span> -->
        <!--          </div> -->
        <!--          <div class="flex items-center space-x-0.5"> -->
        <!--            <svg -->
        <!--              xmlns="http://www.w3.org/2000/svg" -->
        <!--              class="time-icon" -->
        <!--              fill="none" -->
        <!--              viewBox="0 0 24 24" -->
        <!--              stroke="currentColor" -->
        <!--            > -->
        <!--              <path -->
        <!--                stroke-linecap="round" -->
        <!--                stroke-linejoin="round" -->
        <!--                stroke-width="2" -->
        <!--                d="M8 10h.01M12 10h.01M16 10h.01M9 16H5a2 2 0 01-2-2V6a2 2 0 012-2h14a2 2 0 012 2v8a2 2 0 01-2 2h-5l-5 5v-5z" -->
        <!--              /> -->
        <!--            </svg> -->
        <!--            <span>4</span> -->
        <!--          </div> -->
        <!--        </div> -->
      </div>
    </div>
    <DropIndicator v-if="state.type === 'is-dragging-over' && state.closestEdge" :edge="state.closestEdge" gap="8px" />
  </div>
</template>

<script setup lang="ts">
import type { SelectOption } from 'naive-ui'
import { combine } from '@atlaskit/pragmatic-drag-and-drop/combine'
import { draggable, dropTargetForElements } from '@atlaskit/pragmatic-drag-and-drop/element/adapter'
import { attachClosestEdge, extractClosestEdge } from '@atlaskit/pragmatic-drag-and-drop-hitbox/closest-edge'
import DOMPurify from 'dompurify'
import { NAvatar } from 'naive-ui'
import { defineProps, onMounted, reactive, ref, watch } from 'vue'
import api from './api'
import DropIndicator from './drop-indicator.vue'

const props = withDefaults(defineProps<{
  task: object
  flowList: any[]
  projectUsers: any[]
}>(), {
  task: () => ({}),
  flowList: () => [],
  projectUsers: () => [],
})

const emit = defineEmits(['refresh'])

const currentFlowItemId = ref(0)

const localTask = ref({ ...props.task })

// 任务状态变更事件
async function handleUpdateFlowItem(value: string, option: SelectOption) {
  const { data } = await api.updateTask({ project_id: localTask.value.projectId, task_id: localTask.value.id, flow_item_id: value })
  console.log(`任务变更返回-->${data}`)
  console.log(data)
  $message.success('任务状态变更成功')
  console.error(`value: ${JSON.stringify(value)}`)
  console.error(`option: ${JSON.stringify(option)}`)
  // 通知更新页面数据
  localTask.value = data

  currentFlowItemId.value = data.flowItemId
  emit('refresh', true)
  // 重新设置任务列表
  // 如果失败了呢，回到原来的去，这里还要记录一下
}

// 将 flowList 映射为 n-select 所需的选项格式
// const options = ref(props.flowList.map(item => ({
//   label: item.name,
//   value: item.id,
//   // 可以根据 status 设置不同的颜色
//   // color: getColorByStatus(item.status)
// })));

const options = computed(() => props.flowList.map(item => ({
  label: item.name,
  value: item.id,
})))

function handleSelectClick() {
  console.log('handleSelectClick -------》')
}

// 任务成员列表
const taskUsers = ref([])

async function getTaskUserInfo(ids) {
  taskUsers.value = props.projectUsers.filter(user => ids.value.includes(user.id))
  // console.error('taskUsers.value is ', taskUsers.value)
}

const ids = ref([])

watch(() => props.task, (newData) => {
  if (newData) {
    console.log('newData', newData)
    localTask.value = newData
    // 设置当前所属工作流
    // console.log('task这里需要执行一下....', newData)
    currentFlowItemId.value = newData.flowItemId
    if (newData && Array.isArray(newData.task_user)) {
      // console.log('进到这里......')
      // 使用 map 方法提取每个元素的 id
      ids.value = newData.task_user.map(item => item.userid)
      // console.error(`ids is ${ids.value}`)
      getTaskUserInfo(ids)
    }
  }
}, { deep: true, immediate: true })

function cleanHtml(htmlText) {
  const cleanTxt = DOMPurify.sanitize(htmlText, {
    ALLOWED_TAGS: [], // 不允许任何标签
    ALLOWED_ATTR: [], // 不允许任何属性
  })
  return cleanTxt
}

function dropdownOptions(restOptions) {
  return restOptions.map(option => ({
    key: option.name,
    label: option.name,
  }))
}

const state = reactive({
  type: 'idle',
  container: null,
  closestEdge: null,
})
const taskRef = ref(null)
onMounted(() => {
  const element = taskRef.value
  if (!element)
    return
  combine(
    draggable({
      element,
      getInitialData() {
        // return getTaskData(props.task)
        return props.task
      },
    }),
    dropTargetForElements({
      element,
      canDrop({ source }) {
        if (source.element === element) {
          return false
        }
        return true
      },
      getData({ input }) {
        // const data = getTaskData(props.task)
        const data = props.task
        return attachClosestEdge(data, {
          element,
          input,
          allowedEdges: ['top', 'bottom'],
        })
      },
      getIsSticky() {
        return true
      },
      onDragEnter({ self }) {
        const closestEdge = extractClosestEdge(self.data)
        state.type = 'is-dragging-over'
        state.closestEdge = closestEdge
      },
      onDrag({ self }) {
        const closestEdge = extractClosestEdge(self.data)
        if (state.type === 'is-dragging-over' && state.closestEdge === closestEdge) {
          return
        }
        state.type = 'is-dragging-over'
        state.closestEdge = closestEdge
      },
      onDragLeave() {
        state.type = 'idle'
      },
      onDrop() {
        state.type = 'idle'
      },
    }),
  )
})
</script>

<style scoped>
.title {
  letter-spacing: 0.025em;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  text-overflow: ellipsis;
  overflow: hidden;
  white-space: nowrap;
  color: #475569;
  -webkit-line-clamp: 1; /* 限制在一个块元素显示的文本的行数 */
}

.desc {
  color: #94a3b8;
  font-size: 0.75rem;
  line-height: 1rem;
  margin-top: 1px;
}

.time-line {
  flex-wrap: wrap;
  display: flex;
  margin-top: 0.5rem;
}

.time-box {
  color: #1e293b;
  padding: 0.25rem 0.375rem;
  background-color: #e9eef5;
  align-items: center;
  border-radius: 0.25rem;
  display: inline-flex;
  font-family:
    Inter,
    ui-sans-serif,
    system-ui,
    -apple-system,
    BlinkMacSystemFont,
    Segoe UI,
    Roboto,
    Helvetica Neue,
    Arial,
    Noto Sans,
    sans-serif,
    Apple Color Emoji,
    Segoe UI Emoji,
    Segoe UI Symbol,
    Noto Color Emoji;
  font-size: 0.75rem;
  font-weight: 500;
  justify-content: center;
  letter-spacing: 0.025em;
  line-height: 1;
  transition-duration: 0.2s;
  transition-property: all;
  transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1);
  vertical-align: baseline;
}

.time-box > :not([hidden]) ~ :not([hidden]) {
  --tw-space-x-reverse: 0;
  margin-left: calc(0.25rem * (1 - var(--tw-space-x-reverse)));
  margin-right: calc(0.25rem * var(--tw-space-x-reverse));
}

.time-icon {
  width: 0.875rem;
  height: 0.875rem;
}

.last-text-box {
  color: #94a3b8;
  font-size: 0.75rem;
  line-height: 1rem;
  align-items: center;
  display: flex;
}

.last-text-box > :not([hidden]) ~ :not([hidden]) {
  --tw-space-x-reverse: 0;
  margin-left: calc(0.125rem * (1 - var(--tw-space-x-reverse)));
  margin-right: calc(0.125rem * var(--tw-space-x-reverse));
}

.item {
  display: flex;
  box-sizing: border-box;
  grid-template-areas: initial;
  grid-template-columns: auto 1fr auto;
  grid-template-rows: initial;
  column-gap: 8px;
  -webkit-box-align: center;
  //width: 100%;
  width: calc(100% - 10px);
  padding: 8px;
  background-color: #ffffff;
  border-radius: 8px;
  position: relative;
  cursor: grab;
  box-shadow:
    0 1px 1px #091e423f,
    0 0 1px #091e4221;
}

.relative {
  //position: relative;
  //padding: 6px 10px;
  //padding-top: 10px;
  margin-top: 10px;
}

.flex {
  display: flex;
}

.priority-color {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 4px;
  max-height: 100%;
  border-radius: 8px 8px 0 0;
  background-color: rgb(75, 112, 243);
}

.text-sm {
  font-size: 0.875rem;
}

.bg-white {
  background-color: white;
}

.flex-row {
  flex-direction: row;
}

.items-center {
  align-items: center;
}

.border {
  border-width: 1px;
}

.border-solid {
  border-style: solid;
}

.rounded {
  border-radius: 0.25rem;
}

.p-2 {
  padding: 0.5rem;
}

.pl-0 {
  padding-left: 0;
}

.hover\:bg-slate-100:hover {
  background-color: #f1f5f9;
}

.hover\:cursor-grab:hover {
  cursor: grab;
}

.w-6 {
  width: 1.5rem;
}

.justify-center {
  justify-content: center;
}

.truncate {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.flex-grow {
  flex-grow: 1;
}

.flex-shrink {
  flex-shrink: 1;
}

.opacity-40 {
  opacity: 0.4;
}

.marginTop {
  margin-top: 10px;
}
</style>
